//-----------------------------------------------------------------------------------------------
//										Selector
//-----------------------------------------------------------------------------------------------

var Selector_Instances = new Array();
var Selector_heightitem	= 22; 
var Selector_widthscroll = 15; // 10;
var Selector_heightscroll = 15; // 13;
var Selector_interval = 70;
var Selector_leftbutton	= false;
var Selector_porcmarker	= 2;
var Selector_inputtimer;
var Selector_inputkeytimelag = 200;

function WebSelector(id)
{
	// Atributos publicos
	this.value		      = ""; 
    this.description	  = "";
    
	this.width	 		  = 200; // en pixels
	this.size			  = 10;  // cantidad maxima de items
	this.getListFunction  = "";
	this.thereAreItems    = false;
	this.length           = 0;
	this.cssClass         = "";
	    	
	// Atributos privados
	this.id				  = id;
	this.itemSelected	  = -1;
	this.descSelected     = "";
			
	this.iswritten		  = false;
	this.isexpanded		  = false;
	this.enabled		  = true;
    this.active	          = true;
    	
	// Funciones publicas
	this.getValue		  = Selector_GetValue;
	this.getDescription	  = Selector_GetDescription;
	this.setValue		  = Selector_SetValue;
	this.setDescription	  = Selector_SetDescription;	
	this.dispose		  = Selector_Dispose;
    this.clone            = Selector_Clone;
    
	this.disable 		  = Selector_Disable;
    this.enable			  = Selector_Enable;	    
    this.setActive		  = Selector_SetActive;	    
    this.setVisible		  = Selector_SetVisible;		
    this.clear		      = Selector_Clear;	
    
    this.show             = Selector_Show;
    	
	// Eventos Personalizados
	this.evalOnSelect = Selector_EvalOnSelect;
	this.evalOnUnselect = Selector_EvalOnUnselect;	
	this.onSelect;
	this.onUnselect;
	
	Selector_Instances[id] = this;	
}

//Devuelve el valor que identifica al item seleccionado 
//Si el selector esta inactivo, devuelve directamente la descripcion 
function Selector_GetValue()
{
    if(this.iswritten) {
        var objValue;
        
        if(this.active)
            objValue = document.getElementById(this.id + "_value");
        else
            objValue = document.getElementById(this.id);
                
        return objValue.value;
    }
    else {
        return this.value;
    }
}

//Devuelve la descripcion del item seleccionado (el valor del input)
function Selector_GetDescription()
{
    if(this.iswritten) {
        var objDesc = document.getElementById(this.id);
        return objDesc.value;
    }
    else {
        return this.description;
    }    
}

//Establece el valor que identifica al item seleccionado 
function Selector_SetValue(value)
{
    if(this.iswritten) {
        var objValue =  document.getElementById(this.id + "_value");
        objValue.value = value;
    }
    else {
        this.value = value;
    }        
}

//Establece la descripcion del item seleccionado (el valor del input)
function Selector_SetDescription(desc)
{
    if(this.iswritten) {
        var objDesc = document.getElementById(this.id);
        objDesc.value = desc;
        
        var objDescH = document.getElementById(this.id + "_desc");
        objDescH.value = desc;
    }
    else {
        this.description = desc;
    }       
}

//Saca el objeto de la pagina
function Selector_Dispose()
{
    if(this.iswritten) {
	    var divcont = document.getElementById("divcont" + this.id);
    	
	    if(divcont) {
	        if(divcont.parentElement)
	            divcont.parentElement.removeChild(divcont);
	        else
	            divcont.parentNode.removeChild(divcont);
	    }
    }
     
	if(FocusManager.isFocused(this))
		FocusManager.controlonfocus = "";
    
	delete Selector_Instances[this.id];
}

function Selector_Clone(newId)
{
    var newSelector = new WebSelector(newId);

	newSelector.width = this.width;
	newSelector.size = this.size;
	newSelector.getListFunction = this.getListFunction;
	newSelector.length = this.length;
	newSelector.cssClass = this.cssClass;
	
	newSelector.enabled = this.enabled;
	newSelector.active = this.active;
	
	newSelector.onSelect = this.onSelect;	
	newSelector.onUnselect = this.onUnselect;	
	
    return newSelector;
}

//Activo el Selector
function Selector_Enable()
{
	this.enabled = true;

    if(this.iswritten) {	
	    var campo = document.getElementById(this.id);
	    campo.disabled = false;
        campo.className = "input";
    	
        // Registro el estado en la pagina
        var objEnabled =  document.getElementById(this.id + "_enabled");
        objEnabled.value = "True";
    }
}

//Desactivo el Selector
function Selector_Disable()
{
	this.enabled = false;
	
    if(this.iswritten) {		
	    var campo = document.getElementById(this.id);
	    campo.disabled = true;
        campo.className = "inputDisabled";
        
        // Registro el estado en la pagina
        var objEnabled =  document.getElementById(this.id + "_enabled");
        objEnabled.value = "False";
    }
}

function Selector_SetActive(valor)
{
	this.active = valor;

    if(this.iswritten) {	
        // Registro el estado en la pagina
        var objActive =  document.getElementById(this.id + "_active");
        
        if(valor)
            objActive.value = "True";
        else
            objActive.value = "False";
    }
}

//Muestra/Oculta el control
function Selector_SetVisible(value)
{
    if(this.iswritten) {	
	    var cont = document.getElementById("divcont" + this.id);
	    ShowHideObject(cont, value);
	}
}

//Limpia el contenido del control
function Selector_Clear()
{
    Selector_ClearValue(this.id);
    Selector_ClearDescription(this.id);
}

function Selector_Fill(id, doc)
{
    var findvalue = doc.firstChild.getAttribute("valor");
    var haymas = (doc.firstChild.getAttribute("haymas") == "si");
    var items = doc.getElementsByTagName('item'); // This remove all that uggly '#text' nodes
        
    var mSelector = Selector_Get(id);

    var key;
    var value;
    var html = "";
    var length = items.length;
         
    var ini;
    var fin;
        
    mSelector.itemSelected = -1;
    
    if(length>0)
    {
        html += "<table selector=\"yes\" class=\"listTable\" cellpadding=0 cellspacing=0>\n";
	    
        for (var i=0;i<length;i++)
        {
            idvalue = getNodeValue(items[i], 'id');
            value = getNodeValue(items[i], 'desc');
        
            // Resalto la seleccion
            ini = value.toUpperCase().indexOf(findvalue);
            fin = (ini==-1)? 0 : ini + findvalue.length;
            showablevalue = "&nbsp;" + value.substring(0, ini) + "<B>" + value.substring(ini, fin) + "</B>" + value.substring(fin, value.length) + "&nbsp;";

            func = "onmousemove=\"Selector_ItemSelection('"+id+"',"+i+",'move', event)\" onmouseup=\"Selector_ItemSelection('"+id+"',"+i+", 'up', event)\" ";

            if(i==mSelector.itemSelected)
            {
                mSelector.descSelected = value;
                aclass = "selectedItem";
            }
            else
            {
                aclass = "unselectedItem";
            }
                
            html += "<tr>\n";
            html += "   <td selector=\"yes\" nowrap id=\"item_"+id+"_"+i+"\" class=\""+aclass+"\" style=\"height:"+Selector_heightitem+"px; width:"+(mSelector.width+2)+"px; cursor:default\" "+func+">\n";
            html +=         showablevalue + "\n";
            html += "       <input type=\"hidden\" id=\"value_"+id+"_"+i+"\" value=\""+idvalue+"\">\n";
            html += "       <input type=\"hidden\" id=\"description_"+id+"_"+i+"\" value=\""+value+"\">\n";
            html += "   </td>\n";
            html += "</tr>\n"; 
        }

        if(haymas)
        {
            html += "<tr>\n";
            html += "   <td selector=\"yes\" class=\"unselectedItem\">\n";
            html += "       &nbsp;...\n";
            html += "   </td>\n";
            html += "</tr>\n";         
        }
        
        html += "</table>\n";	

        var obj = document.getElementById("selector_" + id);
        obj.innerHTML = html;
        
        mSelector.thereAreItems = true;
        mSelector.length = length;
        
        Selector_ExpandSelector(id);
    }
    else
    {
        mSelector.thereAreItems = false;
        mSelector.itemSelected = -1;
        Selector_ColapseSelector(id);        
    }
}

function Selector_Show(container)
{
    var aclass;
    var func;
    var maxlength;
    var inputClass;
    
    var strenabled;

    if (this.maxlength == 0)
        maxlen = "";
    else
        maxlen = "maxlength=\"" + this.maxlength + "\"";

    if (this.enabled) {
        inputClass = "input";
        strenabled = "";
    }
    else {
        inputClass = "inputDisabled";
        strenabled = "readonly = \"readonly\"";
    }
                
    func = "onfocusin=\"Selector_SetFocus(\'" + this.id + "\');\" onfocus=\"Selector_SetFocus(\'" + this.id + "\');\" onkeyup=\"Selector_InputKeyUp('" + this.id + "', event)\" onkeydown=\"Selector_MoveInTheList('" + this.id + "', event); Selector_InputKeyDown('" + this.id + "', event)\" ";
    aclass = "\"SelectorItem\"";

    var html = "";
    
    // Dibujado del control
    html += "<span ID=\"divcont" + this.id + "\" name=\"divcont" + this.id + "\">";
    html += "   <table ID=\"cmb" + this.id + "\" name=\"cmb" + this.id + "\" cellpadding=0 cellspacing=0 width=\"" + (this.width + 2) + "\" z-index:0; table-layout:fixed\">";
    html += "       <tr><td selector=\"yes\" nowrap class=" + aclass + " ID=\"selec" + this.id + "\" style=\"cursor:default\">";
    html += "           <input ID=\"" + this.id + "\" name=\"" + this.id + "\" " + maxlen + " autocomplete=\"off\" value=\"" + this.description + "\" selector=\"yes\" " + strenabled + " class=\"" + inputClass + "\" style=\"width:" + this.width + "px\" type=\"text\" " + func + ">";
    html += "           <input ID=\"" + this.id + "_desc\"  name=\"" + this.id + "_desc\" value=\"" + this.description + "\" selector=\"yes\" type=\"hidden\">";
    html += "           <input ID=\"" + this.id + "_value\" name=\"" + this.id + "_value\" value=\"" + this.value + "\" selector=\"yes\" type=\"hidden\">";
    html += "           <input ID=\"" + this.id + "_enabled\" name=\"" + this.id + "_enabled\" value=\"" + this.enabled.toString() + "\" selector=\"yes\" type=\"hidden\">";
    html += "           <input ID=\"" + this.id + "_active\" name=\"" + this.id + "_active\" value=\"" + this.active.toString() + "\" selector=\"yes\" type=\"hidden\">";
    html += "       </td></tr>";
    html += "   </table>";
    html += "   <div ID=\"selector_" + this.id + "\" name=\"selector_" + this.id + "\" style=\"position:absolute; visibility:hidden; z-index:10\">";
    html += "   </div>";
    html += "</span>";
    
    container.innerHTML = html;
    
  	this.iswritten = true;
}

//-------------Manejo de Eventos

function Selector_ColapseSelector(id)
{
	var mSelector = Selector_Get(id);
	var div  = document.getElementById("selector_" + mSelector.id);
	
	if (!mSelector.isexpanded) return; //Se pide replegar el selector, pero ya esta replegado
	
	ShowHideObject(div, false);
	mSelector.isexpanded = false;
}

function Selector_ExpandSelector(id)
{
	var mSelector = Selector_Get(id);
	var div  = document.getElementById("selector_" + mSelector.id);
	
	// Si la lista tiene algo, la muestro
	if(mSelector.thereAreItems)
	{
		ShowHideObject(div, true);
	    mSelector.isexpanded = true;
	}
}

function Selector_InputKeyUp(id, e)
{
	var mSelector = Selector_Get(id);
	if(!mSelector.active) return;
	if(!mSelector.enabled) return;
	
    // trapeo caracteres invalidos para buscar
    if( !((e.keyCode>=33) && (e.keyCode<=40)) // Flechas, Pag, Home, Ini
     && !((e.keyCode>=16) && (e.keyCode<=18)) // Ctrl, Alt, Shift
     && (e.keyCode!=13) && (e.keyCode!=9) ) { // Enter y Tab

        clearTimeout(Selector_inputtimer);
        Selector_inputtimer = setTimeout("Selector_InputKeyUpAux('" + id + "')", Selector_inputkeytimelag);
    }
}

function Selector_InputKeyUpAux(id)
{
	var mSelector = Selector_Get(id);
    var desc = mSelector.getDescription();

    Selector_ClearValue(id);

    if(desc!="")
    {
        eval(mSelector.getListFunction + '(\"'+mSelector.id+"\",\""+desc+'\", '+mSelector.size+')');
    }
    else
    {
        mSelector.thereAreItems = false;
        mSelector.itemSelected = -1;
        Selector_ColapseSelector(id);
    }
}

function Selector_InputKeyDown(id, e)
{
	var mSelector = Selector_Get(id);
	if(!mSelector.enabled) return;

    if(e.keyCode==9) { // Tab
        Selector_DisposeFocus(id);  
    }  
}

function Selector_MoveInTheList(id, e)
{
	var mSelector = Selector_Get(id);
	if(!mSelector.active) return;
	if(!mSelector.enabled) return;
	if(!mSelector.isexpanded) return;

    // Para ajoba
    if(e.keyCode==40) {
        if(mSelector.itemSelected < mSelector.length-1)
            Selector_ToggleItem(id, mSelector.itemSelected+1);
    
        Common.cancelBubble(e);
    }
    // Pa rriba
    else if(e.keyCode==38) {
        if(mSelector.itemSelected > 0)
            Selector_ToggleItem(id, mSelector.itemSelected-1);
    
        Common.cancelBubble(e);
    }
    else if(e.keyCode==13) {
        Selector_ChoiceAnItem(id, mSelector.itemSelected);
        
        Common.cancelBubble(e);        
    }
}

//Esta funcion manejan la seleccion de los items de la lista
function Selector_ItemSelection(id, index, action, e)
{
	var mSelector = Selector_Get(id);
    if (!FocusManager.isFocused(mSelector)) return -1
	
	if (action=="move")
	{
		Selector_ToggleItem(id, index);
	}
	
	else if (action=="down")
	{
	    // 0: Firefox / 1: IE
		if( (e.button==0) || (e.button==1) )
		{
			Selector_ToggleItem(id, index);
		}
	}

	else if (action=="up")
	{
	    // 0: Firefox / 1: IE
		if( (e.button==0) || (e.button==1) )
		{
            Selector_ChoiceAnItem(id, index);
		}
	}
}

function Selector_ChoiceAnItem(id, index)
{
    if(index==-1) return -1;
    
	var mSelector = Selector_Get(id);
	
    var objValue =  document.getElementById(id + "_value");
    objValue.value = document.getElementById("value_"+id+"_"+index).value;
    
    var objDescH =  document.getElementById(id + "_desc");
    objDescH.value = document.getElementById("description_"+id+"_"+index).value;

    var objDesc =  document.getElementById(id);
    objDesc.value = document.getElementById("description_"+id+"_"+index).value;
    
	Selector_ColapseSelector(id);
	objDesc.focus();
	
	// Cuando se elige un item, se dispara el evento onSelect
	mSelector.evalOnSelect();
}

//Esta funcion maneja los prendidos de la lista de items de busqueda
function Selector_ToggleItem(id, index)
{
	var mSelector = Selector_Get(id);
	var celda;
	
	if(mSelector.itemSelected!=-1)
	{
		celda = document.getElementById("item_"+id+"_"+mSelector.itemSelected);
	    celda.className = "unselectedItem";
	}	
	if (index!=-1)
	{
	    celda = document.getElementById("item_"+id+"_"+index);	
		celda.className = "selectedItem";
	}
	
	mSelector.itemSelected = index;
	mSelector.descSelected = document.getElementById("description_"+id+"_"+index).value;
}

function Selector_ClearValue(id)
{
    var objValue =  document.getElementById(id+"_value");
    
    if(objValue.value!="") {
        objValue.value = "";
        
        // disparo el evento unselect
        var mSelector = Selector_Get(id);
        mSelector.evalOnUnselect();
    }
}

function Selector_ClearDescription(id)
{
    var objValue =  document.getElementById(id+"_value");
    
    if(objValue.value=="")
    {
        var objDescH =  document.getElementById(id+"_desc");
        objDescH.value = "";

        var objDesc =  document.getElementById(id);
        objDesc.value = "";
    }
}


//----------------Eventos Personalizados

function Selector_EvalOnSelect()
{
    eval(this.onSelect);
}

function Selector_EvalOnUnselect()
{
    eval(this.onUnselect);
}


//----------------Funciones de foco

FocusManager.registerControl("Selector_DisposeFocus");

function Selector_DisposeFocus(id)
{
    var mselector = Selector_Get(id);
    
    if(mselector)
    {
    	Selector_ColapseSelector(id);
	
        if(mselector.active)
            Selector_ClearDescription(id);
            
	    var input = document.getElementById(id);
        input.className = "input";
    }
}

function Selector_SetFocus(id)
{
    var mselector = Selector_Get(id);
    
    if( (mselector) && (mselector.enabled) ) {
	    FocusManager.setFocus(id);
	    
	    if(mselector.enabled) {
		    var input = document.getElementById(id);
            input.className = "inputOnFocus";
            input.focus();
        }
	}
}


//---------------Funciones Externas

//Esta funcion devuelve la lista correspondiente al id pasado como parametro
function Selector_Get(id)
{
	return (Selector_Instances[id])
}


//---------------Funciones Genericas

function getNodeValue(obj, tag)
{
    return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}    

function ShowHideObject(obj, value)
{
	if (value)
		obj.style.visibility = "visible";
	else
		obj.style.visibility = "hidden";
}


